
$(function () {
    String.prototype.startWith = function(s) {
        if (s == null || s === "" || this.length === 0 || s.length > this.length)
            return false;
        if (this.substr(0, s.length) === s)
            return true;
        else
            return false;
        return true;
    }

    String.prototype.endWith = function(s) {
        if (s == null || s === "" || this.length === 0|| s.length > this.length)
            return false;
        if (this.substring(this.length - s.length) === s)
            return true;
        else
            return false;
        return true;
    }

    /**
     * Search plugin logic
     * ===================
     */

    var $body = $("body");

    // Search form
    var $form = $('#search-form'),
        $results = $('#search-results'),
        resultsTemplate = Handlebars.compile($('script[type="text/x-handlebars-template"]', $results).html()),
        $phraseInput = $('input[name=phrase]', $form),
        $filterInput = $('input[name=provider]', $form),
        $cachedInput = $('select[name=cached]', $form),
        $resultLimitInput = $('input[name=resultLimit]', $form),
        $progressSpinner = $('.progress .spinner', $form),
        $progressText = $('.progress .text', $form),
        searchXhr = null;

    function search() {
        // if (!$phraseInput.val().length) {
        //     return;
        // }

        if (searchXhr) {
            searchXhr.abort();
        }

        searchXhr = $.ajax({
            url: pluginRoot + '/by-phrase',
            type: 'GET',
            data: $form.serializeArray(),
            beforeSend: function () {
                $results.empty();
                $progressText.text('Please wait...');
                $progressSpinner.removeClass('done');

                if (history.pushState) {
                    var formParams = $form.serializeObject();
                    var uri = new URI().search(formParams).toString();
                    history.pushState({}, document.title, uri)
                }
            },
            complete: function () {
                $progressSpinner.addClass('done');
                $progressText.text('Completed');
            },
            success: function (response) {
                var vars = $.extend({
                    url: this.url
                }, response.data);

                $results.data(vars);
                $results.html(resultsTemplate(vars));
            },
            error: function (xhr) {
                if (xhr.statusText != 'abort') {
                    openAlert('查询列表失败. Internal server error.');
                }
            }
        });
    }

    var formParams = new URI().search(true);
    populate($form, formParams);

    $phraseInput.on('keyup', _.debounce(search, 1000));
    $filterInput.on('change', search);
    $cachedInput.on('change', search);
    $resultLimitInput.on('change', search);

    //search
    search();

    //upload file
    $("#add-route").bind("click", function () {
        $("input[name='action']").val('install')
        uploadDialog.dialog('open')
        return false
    });


    var uploadDialogButtons = {};
    uploadDialogButtons["提交"] = function() {
        var file = $(this).find("input[name='routeFile']").val();
        if (file === undefined || file === '') {
            alert('文件未选择.')
            return false;
        }
        if (!file.endWith(".xml")) {
            alert('必须是xml文件.')
            return false
        }
        file = file.substring(file.lastIndexOf("\\") + 1)
        if (!file.startWith("codyy-route")) {
            alert('文件名必须以codyy-route开头')
            return false
        }
        $(this).find('form').submit()

    }
    uploadDialog = $('#uploadDialog').dialog({
        autoOpen: false,
        modal   : true,
        width   : '50%',
        buttons : uploadDialogButtons
    });


});

var updateFile = function(bundleId) {
    console.log('bundleId:' + bundleId)
    $("input[name='bundleId']").val(bundleId)
    $("input[name='action']").val('update')
    uploadDialog.dialog('open')
    return false
}

var deleteFile = function (bundleId) {
    if (bundleId === undefined || bundleId === '') {
        alert('ID获取失败。')
    }
    if (!confirm("当前操作不可恢复，是否继续？")) {
        return false;
    }
    $.ajax({
        url: pluginRoot + '/by-phrase?bundleId='+bundleId,
        type: 'DELETE',
        success: function (response) {
            console.log(response.type)
            if (response.type === 'success') {
                alert('删除成功')
                window.location.reload()
                console.log('刷新成功')

            } else {
                alert(response.message)
            }
        },
        error: function (xhr) {
            if (xhr.statusText != 'abort') {
                openAlert('删除失败. Internal server error.');
            }
        }
    });
}
